package grpc

import (
	"context"
	"fmt"
	"gitee.com/captials-team/ubdframe/src/common"
	"gitee.com/captials-team/ubdframe/src/common/utils"
	"gitee.com/captials-team/ubdframe/src/domain/configstc"
	"gitee.com/captials-team/ubdframe/src/domain/converts"
	"gitee.com/captials-team/ubdframe/src/domain/dto/respdata"
	"gitee.com/captials-team/ubdframe/src/domain/interfaces"
	"gitee.com/captials-team/ubdframe/src/pkg/jwtauth"
	v1log "gitee.com/captials-team/ubdframe/src/pkg/logs"
	"gitee.com/captials-team/ubdframe/src/pkg/passwd"
	pbService "gitee.com/captials-team/ubdframe/src/protobufs/pb/service"
	"go.uber.org/dig"
	"time"
)

type AuthServiceServer struct {
	pbService.UnimplementedUserServiceServer

	jwtAuth interfaces.ItfJwtParser

	userDao        interfaces.ItfUser
	loginRecordDao interfaces.ItfUserLoginRecord
	l              v1log.ILog
}

func (s *AuthServiceServer) DoAuth(ctx context.Context, req *pbService.DoAuthRequest) (*pbService.AuthResponse, error) {
	var resp pbService.AuthResponse
	if req.Account == "" || req.Password == "" {
		utils.CopyTo(&respdata.CParamsInvalid, &resp)
		return &resp, nil
	}
	//ctr.l.Debug("auth req %v", req)

	user, err := s.userDao.QueryByAccount(req.Account)
	if err != nil {
		return nil, fmt.Errorf("query err %s", err)
	}
	if user == nil {
		resp.Code = -1
		resp.Message = "account wrong"
		return &resp, nil
	}
	if user.Password != passwd.GenSaltPasswordByMd5(req.Password, user.Salt) {
		resp.Code = -1
		resp.Message = "password wrong"
		return &resp, nil
	}

	//登录
	packet, err := converts.AuthToDataPacket(converts.UserConvertAuthInfo(user), time.Hour*4, s.jwtAuth)
	if err != nil {
		return nil, err
	}
	utils.CopyTo(&packet.Auth, &resp.Data)

	return &resp, nil
}

func (s *AuthServiceServer) CheckAuth(ctx context.Context, req *pbService.CheckAuthRequest) (*pbService.AuthResponse, error) {
	var resp pbService.AuthResponse
	if req.Token == "" {
		return &resp, fmt.Errorf("token invalid")
	}

	packet, err := converts.TokenToAuthDataPacket(req.Token, s.jwtAuth)
	if err != nil {
		return nil, err
	}

	if err := packet.Valid(); err != nil {
		return nil, err
	}

	utils.CopyTo(&packet.Auth, &(resp.Data))

	s.l.Info("%+v", resp.Data)

	return &resp, nil
}

func (s *AuthServiceServer) AddLog(ctx context.Context, req *pbService.AddLogRequest) (*pbService.AddLogResponse, error) {
	var resp pbService.AddLogResponse
	resp.Message = "add success"
	return &resp, nil
}

func NewAuthServiceServer(di *dig.Container, logger v1log.ILog, conf *configstc.UserAppConfig) *AuthServiceServer {
	server := &AuthServiceServer{
		jwtAuth: jwtauth.NewJwtTokenHandler(conf.AuthConfig.SecretKey),
		l:       logger,
	}
	common.ErrPanic(di.Invoke(func(userDao interfaces.ItfUser, userThirdDao interfaces.ItfUserThird, loginRecordDao interfaces.ItfUserLoginRecord, verifyCodeDao interfaces.ItfVerifyCode) {
		server.userDao = userDao
		server.loginRecordDao = loginRecordDao
	}))

	return server
}
